<template>
    <view class="main">
        <header-vue :title="title" :back="true" :backUrl="backUrl"></header-vue>

        <view class="form-card">
            <view class="form-item">
                <text class="label">收货人</text>
                <u-input class="input" inputAlign="right" v-model="form.name" placeholder="请填写收货人姓名" border="none" clearable></u-input>
            </view>
            <view class="form-item">
                <text class="label">联系电话</text>
                <u-input class="input" inputAlign="right" v-model="form.phone" placeholder="请填写收货人手机号" type="number" border="none" clearable maxlength="11"></u-input>
            </view>
            <view class="form-item" @click="showRegion = true">
                <text class="label">所在地区</text>
                <view class="picker-value">
                    <text v-if="!regionDisplay" class="placeholder">请选择收货地址</text>
                    <text v-else>{{ regionDisplay }}</text>
                    <u-icon name="arrow-down" size="16" color="#999"></u-icon>
                </view>
            </view>
            <view class="form-item">
                <text class="label">详细地址</text>
                <view class="textarea-placeholder" v-if="!form.detail">小区楼栋/乡村名称</view>
                <u-textarea 
                    class="textarea"
                    :class="[lineCount > 1 ? 'textarea-lr':'']"
                    v-model="form.detail"
                    :autoHeight="true"
                    :count="false"
                    border="none"
                    confirmType="done"
                    @linechange="linechange"
                />
            </view>
        </view>

        <view class="default-row">
            <text class="default-label">设为默认收货地址</text>
            <u-switch v-model="form.isDefault" size="18" activeColor="#00CE5D"></u-switch>
        </view>

        <fixed-footer>
            <view class="save-btn" @click="save">保存</view>
        </fixed-footer>

        <u-picker 
            :show="showRegion" 
            :columns="regionColumns" 
            title="请选择地区" 
            @change="onRegionPickerChange"
            @confirm="onRegionConfirm" 
            @cancel="showRegion = false"
            @close="showRegion = false"
        />

        
    </view>
</template>
<script>
import headerVue from '@/components/header.vue'
import fixedFooter from '@/components/fixed-footer/index.vue'
import { AddressList, getprovince, getcity, setdefaultAddress, updateAddress } from '@/api/index.js'
import { mapActions, mapGetters } from 'vuex'

export default {
    components: {
        headerVue,
        fixedFooter
    },
    data() {
        return {
            title: '新增地址',
            lineCount: 1,
            form: {
                id: null,
                name: '',
                phone: '',
                region: [], // [省, 市, 区]
                detail: '',
                isDefault: false  // 修改为false，默认不设为默认地址
            },
            showRegion: false,
            // 地区列：[[省名], [市名], [区名]]
            regionColumns: [],
            // 本地缓存，便于根据 id 逐级加载
            provinceList: [],
            cityList: [],
            districtList: [],
            // 待填充的地址详情（用于异步就绪后回显）
            pendingDetailAddress: null,
            // 已选地区的id（提交用）
            selectedProvinceId: 0,
            selectedCityId: 0,
            selectedDistrictId: 0,
            isEditAddress: false,
            addressId: null,
            backUrl:'',
            isClick:''
        }
    },
    computed: {
        ...mapGetters(['addressList']),
        regionDisplay() {
            return (this.form.region && this.form.region.length) ? this.form.region.join(' ') : ''
        }
    },
    onLoad(query) {
        this.tryFillByQuery(query)
        this.getprovinceEvent()
        this.isClick = query.isClick
        this.backUrl = `/views/address/manage?isClick=${this.isClick}`
    },
    methods: {
        ...mapActions(['addAddress', 'updateAddress', 'setDefaultAddress']),
        
        tryFillByQuery(query = {}) {
            const id = query.address_id
            this.addressId = id
            if (id) {
                this.isEditAddress = true
                this.title = '修改地址'
                // 从store获取地址详情
                const address = this.addressList && Array.isArray(this.addressList)
                    ? this.addressList.find(item => Number(item.id) === Number(id))
                    : null
                if (address) {
                    this.pendingDetailAddress = address
                    this.attemptPopulateFromDetail()
                }
            }
        },
        onRegionConfirm(e) {
            // u-picker 确认
            const values = e?.value || []
            this.form.region = values
            // 依据名称反查id，保证提交使用id
            const [pName, cName, dName] = values
            const pObj = this.provinceList.find(item => item && item.name === pName)
            const cObj = this.cityList.find(item => item && item.name === cName)
            const dObj = this.districtList.find(item => item && item.name === dName)
            this.selectedProvinceId = pObj && pObj.id ? pObj.id : 0
            this.selectedCityId = cObj && cObj.id ? cObj.id : 0
            this.selectedDistrictId = dObj && dObj.id ? dObj.id : 0
            this.showRegion = false
        },
        onRegionPickerChange(e) {
            // 级联联动：省变化 -> 刷新市；市变化 -> 刷新区
            const columnIndex = (e && (e.columnIndex ?? e.column)) ?? 0
            // 省列变化
            if (columnIndex === 0) {
                const provinceIndex = (e && (e.index ?? (Array.isArray(e.indexs) ? e.indexs[0] : 0))) ?? 0
                const province = this.provinceList[provinceIndex]
                if (province && province.id) {
                    this.getcityEvent(province.id, 1)
                } else {
                    this.$set(this.regionColumns, 1, [])
                    this.$set(this.regionColumns, 2, [])
                }
            }
            // 市列变化
            if (columnIndex === 1) {
                const cityIndex = (e && (e.index ?? (Array.isArray(e.indexs) ? e.indexs[1] : 0))) ?? 0
                const city = this.cityList[cityIndex]
                if (city && city.id) {
                    this.getcityEvent(city.id, 2)
                } else {
                    this.$set(this.regionColumns, 2, [])
                }
            }
         
        },
        save() {
            // 简单校验
            if (!this.form.name) return uni.showToast({ title: '请填写收货人姓名', icon: 'none' })
            if (!/^1\d{10}$/.test(this.form.phone)) return uni.showToast({ title: '请输入正确手机号', icon: 'none' })
            if (!this.form.region.length) return uni.showToast({ title: '请选择所在地区', icon: 'none' })
            if (!this.form.detail) return uni.showToast({ title: '请填写详细地址', icon: 'none' })
            
            // 构建地址对象
            const addressData = {
                name: this.form.name,
                telephone: this.form.phone,
                // 省市区改为传递id
                province_id: this.selectedProvinceId || 0,
                city_id: this.selectedCityId || 0,
                district_id: this.selectedDistrictId || 0,
                address: this.form.detail
            }

            
            // TODO: 调用后端保存接口，成功后返回
            this.setAddressList(addressData)
           
        },
        linechange(e) {
            this.lineCount = e.detail.lineCount
        },
        getprovinceEvent() {
            getprovince().then((res) => {
                if (res && res.errno === 0) {
                    const list = Array.isArray(res.data) ? res.data : []
                    // 缓存原始数据（含 id/name）
                    this.provinceList = list
                    // 第一列使用 name
                    const provinceNames = list.map(item => item && item.name ? item.name : '')
                    this.regionColumns = [provinceNames]
                    // 预加载第一个省份的城市
                    const firstProvinceId = list[0] && list[0].id
                    if (firstProvinceId) {
                        this.getcityEvent(firstProvinceId, 1)
                    }
                    // 若有待回显的详情，尝试填充
                    this.attemptPopulateFromDetail()
                } else {
                    this.regionColumns = [[]]
                }
            }).catch(() => {
                this.regionColumns = [[]]
            })
        },
        // level: 1 -> 市；2 -> 区/县
        getcityEvent(pid, level = 1) {
            if (!pid) return Promise.resolve()
            return new Promise((resolve) => {
                getcity({ pid }).then((res) => {
                    if (res && res.errno === 0) {
                        const list = Array.isArray(res.data) ? res.data : []
                        const names = list.map(item => item && item.name ? item.name : '')
                        if (level === 1) {
                            this.cityList = list
                            // 设置第二列（市）
                            this.$set(this.regionColumns, 1, names)
                            // 预加载第一个市的区/县
                            const firstCityId = list[0] && list[0].id
                            if (firstCityId) {
                                this.getcityEvent(firstCityId, 2).finally(() => resolve())
                            } else {
                                this.$set(this.regionColumns, 2, [])
                                resolve()
                            }
                        } else if (level === 2) {
                            this.districtList = list
                            // 设置第三列（区）
                            this.$set(this.regionColumns, 2, names)
                            resolve()
                        }
                    } else {
                        if (level === 1) {
                            this.$set(this.regionColumns, 1, [])
                            this.$set(this.regionColumns, 2, [])
                        } else if (level === 2) {
                            this.$set(this.regionColumns, 2, [])
                        }
                        resolve()
                    }
                }).catch(() => {
                    if (level === 1) {
                        this.$set(this.regionColumns, 1, [])
                        this.$set(this.regionColumns, 2, [])
                    } else if (level === 2) {
                        this.$set(this.regionColumns, 2, [])
                    }
                    resolve()
                })
            })
        },
        // 当省市列加载完毕后，按照详情回显到表单
        async attemptPopulateFromDetail() {
            const d = this.pendingDetailAddress
            if (!d || !Array.isArray(this.provinceList) || this.provinceList.length === 0) return
            // 设置基础信息
            this.form.name = d.name || ''
            this.form.phone = d.telephone || ''
            this.form.isDefault = Number(d.isDefault) === 1
            this.form.detail = d.address || d.street || ''

            // 选中省
            this.selectedProvinceId = d.province_id || 0
            this.selectedCityId = d.city_id || 0
            this.selectedDistrictId = d.district_id || 0

            // 加载对应省的市列表
            // await this.getcityEvent(this.selectedProvinceId, 1)
            // // 加载对应市的区列表
            // if (this.selectedCityId) {
            //     await this.getcityEvent(this.selectedCityId, 2)
            // }

            // 设置展示用名称
            const pName = d.province_name || ''
            const cName = d.city_name || ''
            const aName = d.district_name || ''
            this.form.region = [pName, cName, aName].filter(Boolean)

            // 清掉待处理
            this.pendingDetailAddress = null
        },
        async setAddressList(data) {
            let res = null;
            if (this.isEditAddress) {
                data.address_id = this.addressId
                res = await updateAddress(data)
            } else {
                res = await AddressList(data)
            }
            if (res.errno === 0) {
                if (this.form.isDefault) {
                    await setdefaultAddress({
                        address_id:this.isEditAddress ? this.addressId : res.data.address_id
                    })
                }
                
                // 获取实际的地址ID（新增时从接口返回，修改时使用现有ID）
                const actualAddressId = this.isEditAddress ? this.addressId : res.data.address_id
                
                // 构建完整的地址对象
                const fullAddress = {
                    id: actualAddressId,
                    name: data.name,
                    telephone: data.telephone,
                    province_id: data.province_id,
                    city_id: data.city_id,
                    district_id: data.district_id,
                    address: data.address,
                    province_name: this.form.region[0] || '',
                    city_name: this.form.region[1] || '',
                    district_name: this.form.region[2] || '',
                    isDefault: this.form.isDefault ? 1 : 0
                }
                
                // 同步更新store
                if (this.isEditAddress) {
                    // 修改地址：确保ID类型一致
                    const storeId = Number(actualAddressId)
                    this.updateAddress({ id: storeId, address: fullAddress })
                    
                    // 如果修改的是默认地址，需要更新默认地址ID
                    if (this.form.isDefault) {
                        this.setDefaultAddress(storeId)
                    }
                } else {
                    // 新增地址：确保ID类型一致
                    const newId = Number(actualAddressId)
                    const newAddress = { ...fullAddress, id: newId }
                    this.addAddress(newAddress)
                    
                    // 如果设置为默认地址，更新store中的默认地址
                    if (this.form.isDefault) {
                        this.setDefaultAddress(newId)
                    }
                }
                
                // 只有在用户主动勾选"设为默认地址"时才调用后端接口设置默认地址
                if (this.form.isDefault) {
                    try {
                        await setdefaultAddress({
                            address_id: actualAddressId
                        })
                    } catch (error) {
                        // 静默处理错误
                    }
                }
                
                uni.showToast({
                    title: this.isEditAddress ? '修改成功' : '添加成功',
                    icon:'success',
                    success: () => {
                        uni.redirectTo({
                            url:`/views/address/manage?isClick=${this.isClick}`
                        })
                    }
                })
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.main {
    min-height: 100vh;
}

.form-card {
    background: #F5F5F5;
    margin: 16rpx 0;
    padding: 20rpx 0;
}
.form-item {
    position: relative;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 24rpx 24rpx;
    border-bottom: 1rpx solid #F0F0F0;
    background: #FFFFFF;
    &:last-child {
        border-bottom: none;
    }

    .input {
        text-align: right;
        margin-left: 20rpx;
        width: 60%;
        word-break: break-all;
    }
    .textarea-placeholder {
        position: absolute;
        top: 30rpx;
        right: 24rpx;
        font-size: 28rpx;
        z-index: 2;
        color: #999999;
        word-break: break-all;
        pointer-events: none;
        opacity: 0.8;
    }
    .textarea {
        margin-left: 20rpx;
        width: 60%;
        padding: 4rpx 0 0 0 !important;
        text-align: right;
    }

    .textarea-lr {
        text-align: left;
    }
}
.label {
    font-size: 28rpx;
    color: #333333;
    flex-shrink: 0;
    line-height: 1.6;
    max-width: 220rpx;
    word-break: break-all;
}
.picker-value {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr auto;
    column-gap: 8rpx;
    align-items: center;
    justify-items: end;
    color: #333;
    text-align: right;
}
.placeholder {
    color: #999999;
    word-break: break-all;
    opacity: 0.8;
}
.default-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx;
    background: #FFFFFF;
    margin-top: 16rpx;
}
.default-label {
    font-size: 28rpx;
    color: #333333;
}
.save-btn {
    width: 100%;
    height: 80rpx;
    background: linear-gradient( 90deg, #0785CF 0%, #25A4EF 100%);
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(7,133,207,0.1);   
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 600;
    color: #FFFFFF;
}
</style>